// pages/chuangjian/chuangjian.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navH: '',
    navTop: '',
    pageName: "电子名片",
    showNav: false,
    have: false,
    showphonetc: false,
    showmingpiantc: false,
    showerweitc: false,

    uqid: '',
    fenxiangimg: "",
    list: "",
    isguhua: '',
    fenxiangtc1: false,
    shengchengtu:false,

    isShow:false,
    shareurl:''
  },




  /**
   * 生命周期函数--监听页面加载
   */
  tuichuphonetc() {
    this.setData({
      showphonetc: false,
    })
  },
  tuichumingpiantc() {
    this.setData({
      showmingpiantc: false,
    })
  },
  tuichuerweitc() {
    this.setData({
      showerweitc: false,
    })
  },

  todetails(e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../list/list?id=' + id,
    })
  },
  getlist() {
    var that = this;
    ajax('/api/index/product_list', {
      data: {
        uqid: wx.getStorageSync('uqid'),
        fid: 0,
        page: 1,
        limit: 100,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      console.log(res)
      if (res.error == 0) {
        that.setData({
          list: res.data,
        })

      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        })

      }
    })
  },

  onLoad: function (options) {




  },


  tongxunlu() {
    var that = this
    var phonelist = that.data.allmsg.phone.split('/')
    var guhualist = that.data.allmsg.fixed_telephone.split('/')
    wx.addPhoneContact({
      // 公司电话、微信、公司名称、职位、电子邮件、联系地址
      firstName: that.data.allmsg.name,

      mobilePhoneNumber: phonelist[0],

      weChatNumber:that.data.allmsg.wechat_number,
      organization:that.data.allmsg.company_name,
      title:that.data.allmsg.position,
      hostNumber:guhualist[0],
      email:that.data.allmsg.emails,
      addressStreet:that.data.allmsg.personal_company_address
    })
  },


  yulan(){
    wx.previewImage({
      current: this.data.shareurl, 
      urls: [this.data.shareurl] 
    })
  },

  handleDown:function(){
    var that = this;
    console.log(that.data.shareurl)
    wx.showLoading({
      title: '保存中'
    })
    wx.downloadFile({
      url: that.data.shareurl, // 仅为示例，并非真实的资源
      success(res) {
        console.log(res)
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          let path = res.tempFilePath
          wx.saveImageToPhotosAlbum({
            filePath: path,
            success: (res) => {
              wx.hideLoading();

              wx.showToast({
                title: '已保存至您的相册',
                icon: 'none',
                duration: 2000
              })

            },
            fail: function (err) {
              wx.hideLoading();
              if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
                that.setData({
                  isShow: true
                })
              } else if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
                that.setData({
                  isShow: false
                })
                wx.showToast({
                  title: '取消保存',
                  icon: 'none',
                  duration: 2000
                })
              } else if (err.errMsg === 'saveImageToPhotosAlbum:fail:auth denied') {
                that.setData({
                  isShow: true
                })
              }

            }
          })

        }
      }
    })
  },
  handleSetting(e) { 
    var that = this
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      that.setData({
        isShow: false
      })
    } else {
      that.setData({
        isShow: false
      })
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  shengchenghaibao(){
    var that=this
    ajax('/api/index/hb', {
      data: {
        uqid: wx.getStorageSync('uqid'),
        id:that.data.allmsg.id
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      console.log(res)
      if (res.error == 0) {
        that.setData({
          shareurl:res.data.url,
          shengchengtu:true,
          fenxiangtc1:false,
        })

      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        })

      }
    })
  },

  tuichushengchengtu(){
    this.setData({
      shengchengtu:false
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    this.setData({
      fenxiangtc1: false
    })
    // that.getfenxiangtu() 
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#2A2F42',
    })

    this.setData({
      navH: wx.getStorageSync('navHeight'),
      navTop: wx.getStorageSync('navTop'),
    })
    var uqid = wx.getStorageSync('uqid');
    console.log(uqid)
    this.setData({
      uqid: uqid
    })
    if (uqid == '' || uqid == undefined) {
      this.setData({
        islogin: false
      });
    } else {
      this.setData({
        islogin: true,
      });
      console.log('一登陆')
      this.gettmplIds()
      this.getlist()
      var that = this;
      ajax('/api/index/famous', {
        data: {
          uqid: wx.getStorageSync('uqid')
        },
        header: {
          'Accept': 'application/json', // 默认值
        },
      }, res => {
        console.log(res)
        if (res.error == 0) {


          if (res.data.is_mp == 1) {
            that.setData({
              have: res.data.is_mp,
              allmsg: res.data.info
            })
          } else {

          }

        } else {
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 2000
          })

        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      showphonetc: false,
      showmingpiantc: false,
      showerweitc: false,
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  copyText: function (e) {
    console.log(e)
    var str = e.currentTarget.dataset.nr
    wx.setClipboardData({
      data: str,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
              icon: 'none',
              duration: 2000
            })
          }
        })
      }
    })
  },

  del() {
    var that = this
    ajax('/api/index/famous_del', {
      data: {
        uqid: wx.getStorageSync('uqid'),
        famou_id: that.data.allmsg.id
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'delete'
    }, res => {
      console.log(res)
      if (res.error == 0) {
        wx.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 2000
        })
        that.setData({
          have: false,
          showmingpiantc: false
        })



      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        })

      }
    })
  },
  toedit1() {
    var that = this
    wx.navigateTo({
      url: '../chuangjian/chuangjian?type=' + 'edit' + '&id=' + that.data.allmsg.id,
    })
  },

  showerwei() {
    var that = this
    that.setData({
      showerweitc: true
    })
  },



  showtongxunlutc(e) {
    var isguhua = e.currentTarget.dataset.isguhua
    console.log(e)

    this.setData({
      showphonetc: true,
      isguhua: isguhua
    })
  },

  call() {
    if (this.data.isguhua == 1) {
      var that = this
      var phonelist1 = that.data.allmsg.fixed_telephone.split('/')
      wx.makePhoneCall({
        phoneNumber: phonelist1[0],
      })
    } else {
      var that = this
      var phonelist = that.data.allmsg.phone.split('/')
      wx.makePhoneCall({
        phoneNumber: phonelist[0],
      })
    }
  },
  baocuntxl() {
    if (this.data.isguhua == 1) {
      var that = this
      var phonelist1 = that.data.allmsg.fixed_telephone.split('/')
      wx.addPhoneContact({
        firstName: that.data.allmsg.name,
        mobilePhoneNumber: phonelist1[0]
      })
    } else {
      var that = this
      var phonelist = that.data.allmsg.phone.split('/')
      wx.addPhoneContact({
        firstName: that.data.allmsg.name,
        mobilePhoneNumber: phonelist[0]
      })
    }
  },
  callphone() {
    var that = this
    var phonelist = that.data.allmsg.phone.split('/')
    wx.makePhoneCall({
      phoneNumber: phonelist[0],
    })
  },
  /**
   * 用户点击右上角分享
   */
  panduan() {
    var that = this;
    ajax('/api/index/famous', {
      data: {
        uqid: wx.getStorageSync('uqid')
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      console.log(res)
      if (res.error == 0) {


        if (res.data.is_mp == 1) {
          that.setData({
            have: res.data.is_mp,
            allmsg: res.data.info
          })
        } else {
          that.toedit()
        }

      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        })

      }
    })
  },

  showmingpian() {
    this.setData({
      showmingpiantc: true
    })
  },


  toedit() {
    wx.navigateTo({
      url: '../chuangjian/chuangjian?type=' + 'add' + '&id=' + 0,
    })
  },

  //立即获取智能康复计划  && 授权
  bindGetUserInfo(e) {
    var that = this;
    console.log(e.detail.userInfo)

    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      if (that.data.islogin == false) {


        var code = wx.getStorageSync("code");
        ajax('/api/wx_login', {
          data: {
            js_code: code,
            nickname: e.detail.userInfo.nickName,
            avatar: e.detail.userInfo.avatarUrl
          },
          header: {
            'Accept': 'application/json', // 默认值
          },
        }, res => {
          console.log(res)
          if (res.error == 0) {
            wx.setStorageSync("uqid", res.data.uqid)

            that.setData({
              uqid: res.data.uqid,
              session_key: res.data.session_key
            });
            that.gettmplIds()
            that.getlist()

            that.panduan()
            // wx.navigateTo({
            //   url: '../chuangjian/chuangjian?type=' + 'add',
            // })

          } else {
            wx.showToast({
              title: res.message,
              icon: 'none',
              duration: 2000
            })

          }
        })
      } else {
        that.panduan()
        this.gettmplIds()
        // wx.navigateTo({
        //   url: '../chuangjian/chuangjian?type=' + 'add',
        // })
      }
    } else {
      // wx.navigateTo({
      //   url: '../details/details?id='+1 +'&type=1',
      // })
      wx.showToast({
        title: '请先授权！',
        icon: 'none',
        duration: 2000
      })

    }
  },

  gettmplIds() {
    var that = this;
    ajax('/api/index/config_show', {
      data: {
        uqid: wx.getStorageSync('uqid'),
        key: "mbid"
      },
      header: { 
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      console.log(res)
      if (res.error == 0) {
        that.setData({
          tmplIds: res.data.value
        })


      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        })

      }
    })
  },

  dingyuexiaoxi() {
    var that = this
    // wx.requestSubscribeMessage({
    //   tmplIds: [this.data.tmplIds],
    //   success(res) {
    //     if (res[that.data.tmplIds] == 'accept') {
    //       console.log(res)
    //       ajax('/api/index/fxmp', {
    //         data: {
    //           uqid: wx.getStorageSync('uqid'),
    //           id: that.data.allmsg.id,
    //           template_id: that.data.allmsg.template_id,
    //         },
    //         header: {
    //           'Accept': 'application/json', // 默认值
    //         },
    //       }, res => {
    //         console.log(res)
    //         if (res.error == 0) {
    //           that.setData({
    //             fenxiangimg: res.data.url
    //           })

    //           that.setData({
    //             fenxiangtc1: true
    //           })

    //         } else {
    //           wx.showToast({
    //             title: res.message,
    //             icon: 'none',
    //             duration: 2000
    //           })

    //         }
    //       })
    //     }else{

    //     }


    //   },
    //   fail(res) {
    //     console.log(res)
    //   }
    // })


    ajax('/api/index/fxmp', {
      data: {
        uqid: wx.getStorageSync('uqid'),
        id: that.data.allmsg.id,
        template_id: that.data.allmsg.template_id,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      console.log(res)
      if (res.error == 0) {
        that.setData({
          fenxiangimg: res.data.url
        })

        that.setData({
          fenxiangtc1: true
        })

      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        })

      }
    })
  },
  tuichufenxiang1tc(){
    this.setData({
      fenxiangtc1: false
    })
  },
  jujue() {
    this.setData({
      showfenxiangtc: false
    })
  },



  onShareAppMessage: function (options) {
    var that = this;
    that.setData({
      fenxiangtc1: false
    })


    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      // 默认是小程序的名称(可以写slogan等)
      path: '/pages/orther/orther?scene=' + that.data.allmsg.id, // 默认是当前页面，必须是以‘/'开头的完整路径
      imageUrl: that.data.fenxiangimg, //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {

        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      }
    }

    return shareObj
  }
})